import axios from 'axios';
import Nproress from 'nprogress';
import 'nprogress/nprogress.css';
import { getUserTempId } from '@/utils/getUserTempId';
import store from '@/store';

const ajax = axios.create({
  baseURL: '/api',
  timeout: 5000
});

ajax.interceptors.request.use(config => {
  // 请求拦截
  Nproress.start();
  // 统一添加请求头
  config.headers.userTempId = getUserTempId();

  // 获取token 加到请求头上
  const token = localStorage.getItem('token');
  // console.log(store.state.user.user.token);
  if (token) {
    config.headers.token = token;
  }
  return config;
});

ajax.interceptors.response.use(
  response => {
    // 响应拦截
    Nproress.done();
    return response.data;
  },
  err => {
    Nproress.done();
    return Promise.reject(new Error(err.message));
  }
);
export default ajax;
